package my.hnb.android.ultils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.Date;

import my.hnb.android.common.AppInfo;
import my.hnb.android.constant.Constants;
import my.hnb.android.ultils.download.DecompressZip;
import my.hnb.android.ultils.download.ExternalStorage;
import my.hnb.android.view.base.BaseActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.text.InputFilter;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

public class AppUltils {

	public AppUltils() {

	}
	
	public static void forceHideKeyboard(Activity activity) {
		if (activity != null && activity.getCurrentFocus() != null) {
			InputMethodManager inputManager = (InputMethodManager) activity
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
					InputMethodManager.HIDE_NOT_ALWAYS);

		}
	}

	/**
	 * Kiem tra trang thai mang
	 * @author BANGHN
	 * @return
	 */
	public static boolean checkNetworkAccess() {
		boolean res = false;
		try {
			ConnectivityManager cm = (ConnectivityManager) AppInfo.getInstance().getAppContext()
					.getSystemService(Context.CONNECTIVITY_SERVICE);

			if (cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting()
					|| cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting()) {
				MyLog.i("Test Network Access", "Network available!");
				res = true;
			} else {
				MyLog.i("Test Network Access", "No network available!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}
	
	/**
	 * save object vao file
	 * @author: BangHN
	 * @param object
	 * @param fileName
	 * @return: void
	 * @throws:
	 */
	public static void saveObject(Object object, String fileName) {
		try {
			FileOutputStream fos = AppInfo.getInstance().getAppContext().openFileOutput(fileName, Context.MODE_PRIVATE);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(object);
			oos.close();
			fos.close();
		} catch (Throwable e) {
			MyLog.d("Profile", "Error save object: " + e.toString());
			e.printStackTrace();
		}
	}
	
	/**
	 * doc doi tuong tu file
	 * 
	 * @author: BangHN
	 * @version: 1.0
	 * @since: Dec 28, 2011
	 */
	public static Object readObject(String fileName) {
		Object object = null;
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			if (isExistFile(fileName)) {
				fis = AppInfo.getInstance().getAppContext().openFileInput(fileName);
				if (fis != null) {// ton tai file
					ois = new ObjectInputStream(fis);
					object = ois.readObject();

				}
			}
		} catch (Throwable e) {
			object = null;
			MyLog.d("Profile", "Error read object: " + e.toString());
			e.printStackTrace();
		} finally {
			try {
				ois.close();
				fis.close();
			} catch (Exception e) {
			}
		}
		return object;
	}
	
	/**
	 * Kiem tra file ton tai hay khong
	 * @author BangHN
	 * @param fileName
	 * @return
	 */
	public static boolean isExistFile(String fileName) {
		try {
			if (!StringUtil.isNullOrEmpty(fileName)) {
				String[] s = AppInfo.getInstance().getAppContext().fileList();
				for (int i = 0, size = s.length; i < size; i++) {
					if (fileName.equals(s[i].toString())) {
						return true;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * doi don vi dpi <-> pixel
	 * 
	 * @author: BangHN
	 * @version: 1.0
	 * @since: Dec 28, 2011
	 */
	public static int dip2Pixel(Context context, int dips) {
		int ret = (int) (context.getResources().getDisplayMetrics().density * dips + 0.5f);
		return ret;
	}

	/**
	 * set max lengh cho textview
	 * 
	 * @author: BangHN
	 * @version: 1.0
	 * @since: Dec 28, 2011
	 */
	public static void setEditTextMaxLength(EditText edText, int maxLength) {
		InputFilter[] inputFilters = new InputFilter[1];
		inputFilters[0] = new InputFilter.LengthFilter(maxLength);
		edText.setFilters(inputFilters);
	}
	
	
	/**
	 * Xoa file DB
	 * 
	 * @author banghn
	 */
	public static void deleteDatabase() {
		try {
			File file = new File(ExternalStorage.getFileDBPath().getAbsolutePath(), Constants.DATABASE_NAME);
			file.delete();
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}

	/**
	 * Kiem tra file databse ton tai hay khong 
	 * @author BANGHN
	 * @return
	 */
	public static boolean checkExistsDataBase() {
		boolean isExistData = false;
		SQLiteDatabase checkDB = null;
		try {
			checkDB = SQLiteDatabase.openDatabase(ExternalStorage.getFileDBPath() + "/" 
					+ Constants.DATABASE_NAME, null, SQLiteDatabase.OPEN_READONLY);
			if (checkDB != null) {
				isExistData = true;
			}
		} catch (SQLiteException e) {
			// database doesn't exist yet.
			MyLog.d("SQLCheck", "checkExistsDataBase : " + e.toString());
		} catch (Throwable e) {
			MyLog.d("SQLCheck", "checkExistsDataBase : " + e.toString());
		} finally {
			try {
				if (checkDB != null) {
					checkDB.close();
					checkDB = null;
				}
			} catch (Exception e) {
			}
		}
		return isExistData;
	}
	
	
	/**
	 * Copy file database karaoke t asset toi thu muc database
	 * @author BANGHN
	 */
	public static void copyDataBaseFromAssets() {
		AssetManager assetManager = AppInfo.getInstance().getAppContext().getAssets();
		InputStream in = null;
		OutputStream out = null;
		try {
			in = assetManager.open(Constants.DATABASE_NAME +".zip");
			File outFile = new File(ExternalStorage.getFileDBPath(), Constants.DATABASE_NAME + ".zip");
			out = new FileOutputStream(outFile);
			copyFile(in, out);
			in.close();
			in = null;
			out.flush();
			out.close();
			out = null;
		} catch (IOException e) {
			Log.e("tag", "Failed to copy asset file: " + Constants.DATABASE_NAME, e);
		}
	}

	/**
	 * copy file
	 * @author BANGHN
	 * @throws IOException
	 */
	public static void copyFile(InputStream in, OutputStream out) throws IOException {
		byte[] buffer = new byte[1024];
		int read;
		while ((read = in.read(buffer)) != -1) {
			out.write(buffer, 0, read);
		}
	}
	
	/**
	 * Giai nen file zip
	 * @author BANGHN
	 * @param context
	 * @param zipFile
	 * @param destination
	 */
	public static void unzipFile(Context context, File zipFile, File destination ) {
		DecompressZip decomp = new DecompressZip( zipFile.getPath(), 
				 destination.getPath() + File.separator );
		decomp.unzip(context);
	}
	
	
	
	public static Bitmap readImageFromSDCard(String path) {
		Bitmap image = null;
		FileInputStream iStream = null;
		try {
			System.gc();
			iStream = new FileInputStream(path);
			BufferedInputStream bis = null;
			bis = new BufferedInputStream(iStream);
			image = BitmapFactory.decodeStream(bis);
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (iStream != null) {
				try {
					iStream.close();
				} catch (IOException ex) {
					// TODO: handle exception
				}
			}
		}
		return image;
	}
	
	
	public static void showDialogConfirm(final BaseActivity view, String title, CharSequence notice, String ok,
			final int actionOk, String cancel, final int actionCancel, final Object data) {
		if (view != null) {
			AlertDialog alertDialog = new AlertDialog.Builder(view).create();
			alertDialog.setTitle(title);
			alertDialog.setMessage(notice);
			if (ok != null && !Constants.STR_BLANK.equals(ok)) {
				alertDialog.setButton(ok, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						view.onEvent(null, actionOk , data);
						dialog.dismiss();
					}
				});
			}
			if (cancel != null && !Constants.STR_BLANK.equals(cancel)) {
				alertDialog.setButton2(cancel, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						view.onEvent(null, actionCancel , data);
						dialog.dismiss();
					}
				});
			}
			alertDialog.show();
		}
	}
	
	public static int getColor(int id) {
		return AppInfo.getInstance().getAppContext().getResources().getColor(id);
	}
	
	public static Date apkUpdateTime() {
		PackageManager packageManager = AppInfo.getInstance().getAppContext().getPackageManager();
		String packageName = AppInfo.getInstance().getAppContext().getPackageName();
		Date date = null;
		try {
			ApplicationInfo appInfo = packageManager.getApplicationInfo(packageName, 0);
			String appFile = appInfo.sourceDir;
			Long installed = new File(appFile).lastModified();
			date = new Date(installed);
		} catch (NameNotFoundException e) {
			return null; // package not found
		} catch (IllegalArgumentException e) {
		} catch (SecurityException e) {
		}
		return date;
	}
}
